import Cesium from './CesiumModule';
import { viewerObj, clickEntity  } from './CesiumModule';
import { ref,reactive } from 'vue';

// 点击实体弹窗的事件
const entityName = ref('')

const popSty = reactive({
  position: 'absolute',
  top: '0px',
  left: '0px',
  width: '300px',
  height: '200px',
  border: '1px solid #000',
  background: 'white',
  borderRadius: '15px',
  padding: '10px',
  fontSize: '16px',
  display: 'none',
})

const popHandle=(movement)=>{
  const pickedObject = viewerObj.viewer.scene.pick(movement.position);
  // 实体的最后位置
  let staticPosition = movement.position;
  // 记录当前点击的实体
  let currentEntity = null;
  if (Cesium.defined(pickedObject) && clickEntity.includes(pickedObject.id.id)) {
    const entity = pickedObject.id;
    if (entity) {
      currentEntity = entity;
      // 弹窗的宽高
      let [h, w] = [popSty.height.slice(0, -2), popSty.width.slice(0, -2)]
      // 弹窗的位置和内容,20是向上的偏移量
      entityName.value = entity.name;
      popSty.top = movement.position.y - h - 20 + 'px';
      popSty.left = movement.position.x - w / 2 + 'px';
      popSty.display = 'block';
      // 监听地图的渲染事件
      viewerObj.viewer.scene.postRender.addEventListener(() => {
        let changePositon = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewerObj.viewer.scene, currentEntity.position._value);
        // 如果实体的位置发生变化，弹窗的位置也要跟着变化
        if (changePositon.x != staticPosition.x || changePositon.y != staticPosition.y) {
          popSty.top = changePositon.y - h - 20 + 'px';
          popSty.left = changePositon.x - w / 2 + 'px';
          // 更新实体的位置
          staticPosition = changePositon;
        }
      });
    }
  } else {
    // 点击空白处隐藏弹窗，移除监听事件
    popSty.display = 'none';
    if (viewerObj.viewer.scene.postRender._listeners.length > 0) {
      viewerObj.viewer.scene.postRender._listeners = [];
    }
  }
}

export {entityName, popSty, popHandle}
